<?php
	include_once(dirname(__FILE__).'/class.captcha.php');
	include_once(dirname(__FILE__).'/../../lib/email.php');
	include_once(dirname(__FILE__).'/../../admin/includes/classes/class.user.php');

	class AKB_QUESTIONS
	{
		var $_questionId = 0;
		var $captcha = false;
		var $_data = array();
		
		var $pdfObj;

		/**
		* Constructor
		* Setup some variables for this class
		*
		* @return void
		*/
		function AKB_QUESTIONS()
		{
			$GLOBALS['Message'] = '';

			// Get the question id (if any)
			$this->_SetId();
			$this->_SetData();
			
			$GLOBALS['HideQuestionLoginPanel'] = 'none';

			// Hide any disabled sections
			// Email the question
			if (!$GLOBALS['allowEmailQuestion']) {
				$GLOBALS['HideEmailPage'] = 'none';
			} else {
				$GLOBALS['HideEmailPage'] = 'block';
			}

			// Print the question
			if (!$GLOBALS['allowPrintQuestion']) {
				$GLOBALS['HidePrintPage'] = 'none';
			} else {
				$GLOBALS['HidePrintPage'] = 'block';
			}

			// Subscribe to the question
			if (!$GLOBALS['allowSubscribeToQuestions']) {
				$GLOBALS['HideSubscribePage'] = 'none';
			} else {
				$GLOBALS['HideSubscribePage'] = 'block';
			}

			// The edit link for logged in users
			if ((AKB_AUTH::IsLoggedIn()) && (AKB_AUTH::HasAdminAccess())) {
				$GLOBALS['HideEditPage'] = 'block';
			} else {
				$GLOBALS['HideEditPage'] = 'none';
			}
			
			// The PDF link for questions
			if ((isset($GLOBALS['enablePDFExport'])) && ($GLOBALS['enablePDFExport'])) {
				$GLOBALS['HidePDF'] = 'block';
			} else {
				$GLOBALS['HidePDF'] = 'none';
			}
			
			// Comment on the question
			if (!$GLOBALS['allowVisitorComments']) {
				$GLOBALS['HidePanels'][] = 'QuestionCommentsPanel';
				$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
				$GLOBALS['HideCommentOnPage'] = 'none';
			} else {
				$GLOBALS['HideCommentOnPage'] = 'block';
			}

			// If you can't email, print or comment, hide the containing box
			if (!$GLOBALS['allowEmailQuestion'] &&
				!$GLOBALS['allowPrintQuestion'] &&
				!$GLOBALS['allowVisitorComments']) {
				$GLOBALS['HideActionPanel'] = 'none';
			} else {
				$GLOBALS['HideActionPanel'] = 'block';
			}

			// Hide the rating sections
			if (!$GLOBALS['allowQuestionRatings']) {
				$GLOBALS['HideRatePanel'] = 'none';
				$GLOBALS['HideRatingPanel'] = 'none';
				$GLOBALS['HideRatedPanel'] = 'none';
			} else {
				$GLOBALS['HideRatePanel'] = 'block';
				$GLOBALS['HideRatingPanel'] = 'table';
				$GLOBALS['HideRatedPanel'] = 'table';
			}
		}
		
		/**
		* _GetId
		* Gets the current question id
		*
		* @return int
		*/
		function _GetId()
		{
			return $this->_questionid;
		}

		/**
		* _GetId
		* Sets the current question id
		*
		* @return bool Returns true if clean urls is off and $_GET['questionid']
		* is an integer
		*/
		function _SetId()
		{
			// If we arn't using clean urls then getting the id is easy
			if (!$GLOBALS['cleanUrls'] && isset($_GET['questionid'])) {
				$this->_questionid = (int) $_GET['questionid'];
				return true;
			}

			// Get the category from the request_uri and work out its ID
			$path = $_SERVER['REQUEST_URI'];
			if (strstr($path, '/questions/')) {
				$iPos = strpos($path, '/questions/') + strlen('/questions/');
			} else {
				$iPos = 0;
			}
			$id = substr($path, $iPos, strlen($path));
			$id = eregi_replace('/$', '', $id);

			$arrQuestion = explode('/', $id);

			if (sizeof($arrQuestion) >= 1 && is_numeric($arrQuestion[0])) {
				$id = $arrQuestion[0];
			}
			$this->_questionid = $id;
		}

		/**
		* _SetData
		* Populate the $this->_data array with information about the question
		*
		* @return void
		*/
		function _SetData()
		{
			if (is_numeric($this->_GetId())) {
				$questionTable = 'questions';
				$query = "SELECT workflowstatus FROM {$GLOBALS['tablePrefix']}questions WHERE questionid = '".$this->_GetId()."' AND (workflowstatus = '".WF_STATUS_REPENDING."' OR workflowstatus = '".WF_STATUS_PENDING."'  OR workflowstatus = '".WF_STATUS_DISAPPROVED."' )";
				$result = $GLOBALS['AKB_DB']->Query($query);
				
				$workflowQry = "";
				if ($GLOBALS['AKB_DB']->CountResult($query) > 0 && validUrl()) {
					$questionTable = 'questions_history';
					$workflowQry = " AND ( q.workflowstatus = '".WF_STATUS_APPROVED."' OR q.workflowstatus = '".WF_STATUS_AUTO_APPROVED."') ";
				}
				$query = "SELECT q.*, u.username, u.firstname, u.lastname
				FROM `".$GLOBALS['tablePrefix']."users` u, `".$GLOBALS['tablePrefix']."categories` c, `".$GLOBALS['tablePrefix']."categoryassociations` a,
				(`".$GLOBALS['tablePrefix']."question_auth` qa
				RIGHT JOIN `".$GLOBALS['tablePrefix']."$questionTable` q ON qa.questionid = q.questionid)
				WHERE q.questionid='".$this->_GetId()."'
					AND q.userid = u.userid
					AND c.categoryid = a.categoryid
					AND a.questionid = q.questionid
					AND
						(
							((q.startdate < '".$GLOBALS['currDatetime']."') AND ((q.enableexpiry = 1) AND q.expirydate > '".$GLOBALS['currDatetime']."'))
							OR
							((q.startdate < '".$GLOBALS['currDatetime']."') AND (q.enableexpiry = 0))
						)					
					AND q.visible=1
					$workflowQry
					AND (qa.groupid is null ".AKB_AUTH::deriveGroupSQL().")
					ORDER BY q.lastupdated DESC
				";
				$query .= $GLOBALS['AKB_DB']->AddLimit(0, 1);
				
				$result = $GLOBALS['AKB_DB']->Query($query);

				if ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					foreach ($row as $k=>$v) {
						$this->_data[$k] = $v;
					}
				}
			}
		}

		/**
		* HandlePage
		*
		* The main page handling function, this routes to the function that is
		* to handle this page view
		*
		* @return void
		*/
		function HandlePage()
		{
			$offset = '';
			if ($GLOBALS['cleanUrls']) {
				$arrURI = explode('/', $_SERVER['REQUEST_URI']);
				$todo = $arrURI[sizeof($arrURI)-1];
				
				if (is_numeric($todo) && $arrURI[sizeof($arrURI)-2] == '__captcha') {
					$offset = (int) $todo;
					$todo = '__captcha';
				} else {
					$offset = '';
				}

				if (strpos($todo, '&')) {
					$get_parts = explode('&', $todo);
					foreach ($get_parts as $get) {
						if (strpos($get, '=')) {
							$get_data = explode('=', $get);
							$_GET[$get_data[0]] = $get_data[1];
						}
					}
					$todo = $get_parts[0];
				}
			} else if (isset($_GET['todo'])) {
				$todo = $_GET['todo'];
				if (isset($_GET['offset'])) {
					$offset = (int) $_GET['offset'];
				}
			} else {
				$todo = '';
			}
			
			// Determine which function to load
			switch ($todo) {
				case '__savecomment':
					if ($GLOBALS['allowVisitorComments']) {
						if (isset($_POST) && !empty($_POST)) {
							$_SESSION['comment']['name'] = $_POST['name'];
							$_SESSION['comment']['email'] = $_POST['email'];
							$_SESSION['comment']['comment'] = $_POST['content'];
						}
						
						if ($this->CheckCommentForm()) {
							$this->SaveComment();
						} else {
							$this->ShowQuestionPage(true);
						}
					}
				break;
				case '__sendemail':
					if ($GLOBALS['allowEmailQuestion']) {
						$this->SendQuestionEmail();
					}
				break;
				case '__email':
					if ($GLOBALS['allowEmailQuestion']) {
						$this->EmailQuestionPage();
					}
				break;
				case '__print':
					if ($GLOBALS['allowPrintQuestion']) {
						$this->PrintQuestionPage();
					}
				break;
				case '__captcha':
					if ($GLOBALS['useCaptchaCheck']) {
						$this->showCaptchaImg($offset);
					}
				break;
				case '__subscribe':
					if ($GLOBALS['allowSubscribeToQuestions']) {
						$this->ShowSubscribePage();
					}
				break;
				case '__savesubscription':
					if ($GLOBALS['allowSubscribeToQuestions']) {
						$this->SaveSubscriptionDetails();
					}
				break;
				case '__confirm':
					if ($GLOBALS['allowSubscribeToQuestions']) {
						$this->ShowSubscriptionConfirm();
					}
				break;
				case '__unsubscribe':
					if ($GLOBALS['allowSubscribeToQuestions']) {
						$this->ShowUnsubscribePage();
					}
				break;
				case '__unsubscribeconfirm':
					if ($GLOBALS['allowSubscribeToQuestions']) {
						$this->SaveUnsubscribe();
					}
				break;
				case '__unhighlight':
					unset($_SESSION['SearchWords']);
					$this->ShowQuestionPage();
				break;
				case '__topdf':
					$this->MakePDF();
				break;				
				
				case '__edit':
					if (!isset($_SESSION['user'])
						|| !strtolower(get_class($_SESSION['user'])) == 'api_user'
						|| !$_SESSION['user']->verify('question', 'edit')) {
						$this->EditEntry();
					}
				break;
				case '__showadd':
					if (isset($_SESSION['user'])) {
						if( strtolower(get_class($_SESSION['user'])) == 'api_user'
						&& $_SESSION['user']->verify('question', 'edit')) {
							$this->ShowAddEntry();
						}
					}
				break;
				default:
					if (($GLOBALS['cleanUrls']) && (substr($todo,0,2) != "__")) {
						$urlTitle = urldecode(array_pop($arrURI));
						$this->CheckTitleInfo($urlTitle);
					}
				
					$this->ShowQuestionPage();
			}
		}
		
		/**
		* Checks to see if the title in the URL is different to the title from the questionid.
		* If so then we want to return a header 301.
		*
		* Only gets called if we've got cleanURL's on.
		*
		* @return void
		*/
		function CheckTitleInfo($urlTitle) {
			if ((!isset($this->_data['title'])) || ($this->_data['title'] == "")) {
				return false;
			}
			
			$questionTitle = $this->_data['title'];
			
			if (($GLOBALS['AKB_CLASS_HELPER']->_MakeURLNormal($urlTitle) != $questionTitle) && ($GLOBALS['cleanUrls'])) {
				$urlBase = GetUrl('question', $this->_GetId());
				$newURL = $urlBase.$GLOBALS['AKB_CLASS_HELPER']->_MakeURLSafe($questionTitle);
				
				header("HTTP/1.1 301 Moved Permanently");
				header("Location: ".$newURL);
				die();
			}		
		}

		/**
		* IncrementViewCount
		* Increment the number of views for the question
		*
		* @return void
		*/
		function IncrementViewCount()
		{
			$query = sprintf("update %squestions set views=views+1, score=score+1 where questionid='%d'", $GLOBALS['tablePrefix'], $this->_GetId());
			$GLOBALS['AKB_DB']->Query($query);
		}

		/**
		* SaveRating
		* Save the positive or negative rating to the database
		*
		* @return void
		*/
		function SaveRating()
		{
			if ($GLOBALS['allowQuestionRatings'] === true) {
				$arrURI = explode('/', $_SERVER['REQUEST_URI']);

				$query = sprintf("select count(*) from %sratings where questionid='%d' and ip='%s'", $GLOBALS['tablePrefix'], $this->_GetId(), $GLOBALS['AKB_DB']->Quote($_SERVER['REMOTE_ADDR']));
				$rated = $GLOBALS['AKB_DB']->FetchOne($query);
				
				if ((!$GLOBALS['cleanUrls'] && isset($_GET['todo']) && $_GET['todo'] == '__rate')
					|| ($arrURI[sizeof($arrURI)-1] == '__rate' && $rated == 0)) {
					if (isset($_POST['rate'])) {
						$rate = $_POST['rate'];

						if ($rate == 0) {
							$this->SendUnhelpfulRatingEmail();
							$query = sprintf("update %squestions set negvotes=negvotes+1, score=score-".SCORE_MODIFIER." where questionid='%d'", $GLOBALS['tablePrefix'], $this->_GetId());
						} else {
							$query = sprintf("update %squestions set posvotes=posvotes+1, score=score+".SCORE_MODIFIER." where questionid='%d'", $GLOBALS['tablePrefix'], $this->_GetId());
						}

						$GLOBALS['AKB_DB']->Query($query);

						// Save a record indicating this user has rated this article
						// Make sure the post vars are setup
						$_POST['questionid'] = $this->_GetId();
						
						// We only save it if this is unhelpful rating
						if ($rate == 0) {
							$rating = new API_RATING();
							$rating->create();
						}
					}
				}
			}
		}

		/**
		* PrintQuestionPage
		* Displays the print question page
		*
		* @return void
		*/
		function PrintQuestionPage()
		{
			$GLOBALS['Title'] = $this->_data['title'];
			//$GLOBALS['SafeTitle'] = $GLOBALS['AKB_CLASS_HELPER']->_MakeURLSafe($this->_data['title']);
			$GLOBALS['SafeTitle'] = '';
			$GLOBALS['QuestionId'] = $this->_data['questionid'];
			$GLOBALS['QuestionUrl'] = GetUrl('question', $this->_GetId());
			$GLOBALS['Answer'] = $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders($this->_data['answer']);

			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('PrintQuestion');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* ValidatePass [DEPRACTED]
		*
		* Returns true if the user is allowed access and false otherwise
		*
		* @return bool True if access is allowed
		*/
		function ValidatePass()
		{
			$query = 'SELECT categoryid
			FROM '.$GLOBALS['tablePrefix'].'categoryassociations a
			WHERE a.questionid = '.$this->_GetId();

			$result = $GLOBALS['AKB_DB']->Query($query);

			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$auth = $this->CheckPass($row['categoryid']);
				if ($auth) {
					return true;
				}
			}

			return false;
		}


		/**
		* GetAuth
		* Get the authorisation information for either this->_catId if $catid is
		* null (default) or the catid passed in
		*
		* @param mixed $catid The id of the cat to get auth info about
		*
		* @return mixed array(pass, catid) of the cat in the tree whos auth
		* applies to the given $catid or false if there is no such category
		*/
		function GetAuth($catid=null)
		{
			$h =& $GLOBALS['AKB_CLASS_HELPER'];
			if (!isset($h->catsById) || empty($h->catsById)) {
				$h->getCatsInfo();
			}

			if ($catid === null) {
				return false;
			} else if (!isset($h->catsById[$catid])) {
				return false;
			} else {
				$cat = $h->catsById[$catid];
			}

			// If this is a non-root category and this category doesn't have
			// a password, check the parent for a password
			if ($cat['parentid'] > 0 && trim($cat['pass']) == '' ) {
				return $this->GetAuth($cat['parentid']);
			} else {
				return array($cat['pass'], $cat['categoryid']);
			}
		}

		/**
		* CheckPass
		* Check to see if a user is authorised to view this page
		*
		* @return bool True if they can view the page false otherwise
		*/
		function CheckPass($catid)
		{
			list ($pass, $categoryid) = $this->GetAuth($catid);

			// If the password isn't set for this or any parent category, then
			// allow the user to access the category
			if (empty($pass)) {
				return true;
			}

			// If the password is set in the cookie and is right then allow
			// access to the category
			$cookie_name = 'akb_cat_pass_'.$categoryid;
			if (isset($_COOKIE[$cookie_name])
				&& $_COOKIE[$cookie_name] == $pass) {
					return true;
			}

			// Is the user attempting to get access to the category?
			if (isset($_POST['questAuthPass'])
				&& $_POST['questAuthPass'] == $pass) {
				// Save the authorization to a cookie and grant access
				setcookie($cookie_name, $pass, time()+3600*24*365, '/');
				return true;
			}

			return false;
		}
		
		function MakePDF() {
			require_once(dirname(__FILE__).'/../../lib/html2pdf/html2fpdf.php');
			
			$title = $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders($this->_data['title']);
			$answer = $this->_GetAnswer();
			
			$this->pdfObj = new HTML2FPDF();
			$this->pdfObj->AddPage();
			
			$content = $this->FormatPDFHTML($title,$answer);
			
			$this->pdfObj->WriteHTML($content);
			$this->pdfObj->Output($this->FormatPDFTitle($title),"D");
		}
		
		function FormatPDFHTML($title,$answer) {
			$title = strip_tags($title);
			
			$url = GetUrl('question', $this->_GetId());
			
			$header = "<p><u><big>".$GLOBALS['knowledgebaseName']."</big></u></p>";
			$footer = "<small><p><a href=\"".$url."\">".$url."</a></p></small>";
			
			$content = str_replace("<br/>","<br />",$answer);
			$content = strip_tags($content,"<h1><h2><h3><h4><p><br /><br><table><th><tr><tbody><td><ul><ol>");
			
			$content = $header."<p><b>".$title."</b></p><p>".$content."</p>".$footer;
			
			return $content;
		}
		
		function FormatPDFTitle($title) {
			return str_replace(" ","_",$title).".pdf";
		}

		/**
		* ShowQuestionPage
		* Shows the question page
		*
		* bool $comment_session Tell the comment form to use whats in the session as there has probably been an error
		* 
		* @return void
		*/
		function ShowQuestionPage($comment_session=false)
		{
			$catId = 0;
			if ((!$this->QuestionHasAuthCat()) || (!$this->QuestionHasAuthArticle()) || (empty($this->_data))) {
				// Load the question not auth'd panel
				$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
				$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
				$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';
				$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';
				$GLOBALS['HidePanels'][] = 'CommentSubmitted';
				
				$GLOBALS['NotPermittedLink'] = 'javascript: history.go(-1);';
				
				if (empty($this->_data)) {
					$GLOBALS['questionNotPermitted'] = GetLang('questionNotExist');
					$GLOBALS['HideAuthTitle'] = 'none;';
				} else {
					$GLOBALS['questionNotPermitted'] = sprintf(GetLang("questionNotPermitted"),$GLOBALS['pathToKB']."/login.php","mailto:".$GLOBALS['contactEmail']);
				}
				
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				
				return false;
			} else {
				// Increment the number of views for this category
				$this->IncrementViewCount();

				// Do we need to add a rating for this article?
				if ($GLOBALS['allowQuestionRatings'] === true) {
					$this->SaveRating();

					// Should we show the rating bar?
					$query = sprintf("select count(*) from %sratings where questionid='%d' and ip='%s'", $GLOBALS['tablePrefix'], $this->_GetId(), $GLOBALS['AKB_DB']->Quote($_SERVER['REMOTE_ADDR']));
					$rated = $GLOBALS['AKB_DB']->FetchOne($query);
				} else {
					$rated = 0;
				}

				// Get the workflow of current article
				$query = 'SELECT workflowstatus, userid FROM %squestions WHERE questionid = \'%s\'';
				$query = sprintf($query, $GLOBALS['tablePrefix'], $this->_GetId());
				$result = $GLOBALS['AKB_DB']->Query($query);
				$currentQuestion = $GLOBALS['AKB_DB']->Fetch($result);
				
				if ($rated > 0) {
					// Hide the option to rate the question
					$GLOBALS['HideRatingPanel'] = 'none';
				} else {
					// Enable question rating
					$GLOBALS['HideRatedPanel'] = 'none';
					$GLOBALS['RateUrl'] = GetUrl('question', $this->_GetId(), 'todo=__rate');
				}

				$GLOBALS['SubscribeLink'] = GetUrl('question', $this->_GetId(), 'todo=__subscribe');

				// Load the home page of the front end
				if (empty($this->_data)) {
					$this->_SetData();
				}
				
				$GLOBALS['QuestionId']			= $this->_data['questionid'];
				$editUrl = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=editQuestion&amp;questionid='.$this->_GetId();
				$cat = $this->_GetCategories();
				
				$GLOBALS['AKB_CLASS_AUTH']		= new AKB_AUTH;
				
				// Get all the cat that always needs approval
				$query = sprintf("select distinct c.categoryid, c.approvaltype from %scategoryassociations ca, %scategories c  where ca.questionid='%d' and ca.categoryid = c.categoryid ", $GLOBALS["tablePrefix"],$GLOBALS["tablePrefix"], $GLOBALS['QuestionId']);
				$result = $GLOBALS['AKB_DB']->Query($query);

				$catAlwaysReqApp = array();
				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					if ($row['approvaltype'] == CATEGORIES_ALWAYS_APPROVAL) {
						$catAlwaysReqApp[] = $row['categoryid'];
					}
				}
				
				$GLOBALS['SuccessMessage'] = '<div id="successmesg" class="SuccessInfo" style="display:none;" ><img align="left" src="'.$GLOBALS['pathToKB'].'/admin/images/success.gif"/>'.GetLang('QuestionEdited').'</div>';
				if (!validUrl() || !sizeof($catAlwaysReqApp)) {
					$GLOBALS['QuickeditMessage'] = '<a href="javascript: editArticle('.$GLOBALS['QuestionId'].');" rel="nofollow" id="editArticle">'.GetLang('QuickEdit').'</a>';
					$GLOBALS['EditMessage'] = '<a href="'.$editUrl.'" rel="nofollow" id="editArticleBackend">'.GetLang('questEdit').'</a>';
				} else {
					
					// This is a re-pending article.
					if (isset($this->_data['versionid'])) {
						
						if (!$GLOBALS['AKB_CLASS_AUTH']->HasApprovalAccess($catAlwaysReqApp, true) && !($currentQuestion['workflowstatus'] == WF_STATUS_DISAPPROVED && $currentQuestion['userid'] == $_SESSION['user']->userid && isset($GLOBALS['allowsOwnerEditDisapprovedArticles']) && $GLOBALS['allowsOwnerEditDisapprovedArticles'])) {
							$GLOBALS['QuickeditMessage'] = '<a style="color: gray;" href="javascript:alert(\''.GetLang('NoArticleEditPermission').'\');">'.GetLang('QuickEdit').'</a>&nbsp;';
							$GLOBALS['EditMessage'] = '<a style="color: gray;" href="javascript:alert(\''.GetLang('NoArticleEditPermission').'\');">'.GetLang('questEdit').'</a>&nbsp;';
						} else {
							$GLOBALS['Message'] = '<div id="mesg" class="HelpInfo" style="display:none;" ><img align="left" src="'.$GLOBALS['pathToKB'].'/admin/images/info.gif"/>'.GetLang('QuickEditRependingArticleMessage').'</div>';
							$GLOBALS['QuickeditMessage'] = '<a href="javascript: editArticle('.$GLOBALS['QuestionId'].');" rel="nofollow" id="editArticle">'.GetLang('QuickEdit').'</a>';
							$GLOBALS['EditMessage'] = '<a href="'.$editUrl.'" rel="nofollow" id="editArticleBackend">'.GetLang('questEdit').'</a>';
						}
					} else { 
						if (!$GLOBALS['AKB_CLASS_AUTH']->HasApprovalAccess($catAlwaysReqApp, true)) {
							$GLOBALS['Message'] = '<div id="mesg" class="HelpInfo" style="display:none;" ><img align="left" src="'.$GLOBALS['pathToKB'].'/admin/images/info.gif"/>'.GetLang('NoAppPermEditMessage').'</div>';
							$GLOBALS['SuccessMessage'] = '<div id="successmesg" class="SuccessInfo" style="display:none;" ><img align="left" src="'.$GLOBALS['pathToKB'].'/admin/images/success.gif"/>'.GetLang('QuestionEditedRequiresApproval').'</div>';

						}
						$GLOBALS['QuickeditMessage'] = '<a href="javascript: editArticle('.$GLOBALS['QuestionId'].');" rel="nofollow" id="editArticle" >'.GetLang('QuickEdit').'</a>';
						$GLOBALS['EditMessage'] = '<a href="'.$editUrl.'" rel="nofollow" id="editArticleBackend">'.GetLang('questEdit').'</a>';
					}
				}
				
				if (trim($this->_data['firstname']) != '' || trim($this->_data['lastname']) != '') {
					$GLOBALS['QuestionAuthor'] = $this->_data['firstname'].' '.$this->_data['lastname'];
				} else {
					$GLOBALS['QuestionAuthor'] = $this->_data['username'];
				}

				$GLOBALS['Answer']				= $this->_GetAnswer();
				$GLOBALS['Comments']			= $this->_GetComments();
				$GLOBALS['RelatedQuestions'] 	= $this->_GetRelatedQuestions();
				$GLOBALS['Attachments'] 		= $this->_GetAttachments();
				$GLOBALS['BreadCrumbs']			= $this->GetBreadCrumbs();
				
				$GLOBALS['LastUpdatedDisplay'] 	= date("jS \of F, Y",strtotime($this->_data['lastupdated']));
				
				$GLOBALS['CustomFields'] = $this->processCustomFields();

				// Highlighting search terms in the question
				if (!isset($_SESSION['SearchWords'])) {
					$GLOBALS['HideUnhighlight'] = 'none';
				} else {
					$GLOBALS['HideUnhighlight'] = 'block';
				}

				$arr = Array();
				
				if (isset($_SESSION['SearchWords']) && is_array($_SESSION['SearchWords'])) {
					foreach ($_SESSION['SearchWords'] as $word) {
						$arr[] = Array(
							'word' => $word,
							'token' => uniqid('')
						);
					}
				}
				// We need to set the page title before replacing search terms in it
				$GLOBALS['Title'] = $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders(htmlspecialchars($this->_data['title'], ENT_QUOTES, $GLOBALS['charset']));
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['Title']);

				$GLOBALS['LastUpdated'] = date("dS F Y h:i:s a", strtotime($this->_data['lastupdated']));

				if ($GLOBALS['allowQuestionRatings']) {
					$GLOBALS['RatingData'] = $this->_GetRatingData();
				} else {
					$GLOBALS['RatingData'] = '';
				}
				$GLOBALS['MetaKeywords']	= htmlspecialchars($this->_data['metakeywords'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['MetaDescription']	= htmlspecialchars($this->_data['metadescription'], ENT_QUOTES, $GLOBALS['charset']);

				$GLOBALS['PrintUrl'] = GetUrl('question', $this->_GetId(), 'todo=__print');
				$GLOBALS['EmailUrl'] = GetUrl('question', $this->_GetId(), 'todo=__email');
				$GLOBALS['CommentUrl'] = "#content";
//				$GLOBALS['EditUrl'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=editQuestion&amp;questionid='.$this->_GetId();
				
				$GLOBALS['PDFUrl'] = GetUrl('question', $this->_GetId(), 'todo=__topdf');
				
				$GLOBALS['UnhighlightUrl'] = GetUrl('question', $this->_GetId(), 'todo=__unhighlight');

				//$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
				$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
				$GLOBALS['HidePanels'][] = 'QuestionAuthPanel';
				$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';
				$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';
				
				$this->CommentPage($comment_session);
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			}
		}
		
		/**
		* processCustomFields
		* Get the custom fields for this question and then process the snippets and return
		* html.
		*
		* @return string
		*/		
		function processCustomFields() {
			$questionid = $this->_getId();
			
			$customfields = custom_fields_helper::get_custom_fields_by_question($questionid);
			
			$GLOBALS['SearchLink'] = GetUrl("search");
			$outputHTML = "";
			foreach ($customfields as $customfieldid=>$cfObj) {
				$GLOBALS['CustomFieldName'] = $cfObj->name;
				
				$GLOBALS['CustomFieldString'] = "";
				foreach ($cfObj->customFieldDataArray as $cfDataObj) {
					$GLOBALS['CFLink'] = "cfid=".$cfDataObj->customfieldid."&cfdata=".$cfDataObj->data;
					$GLOBALS['CFLinkText'] = $cfDataObj->data;
					$GLOBALS['CustomFieldString'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CustomFieldsFELink').", ";
				}
				
				$GLOBALS['CustomFieldString'] = substr($GLOBALS['CustomFieldString'],0,-2);
				
				$outputHTML .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CustomFieldsFE');
			}
			
			return $outputHTML;
		}

		/**
		* _GetRatingData
		* Get the html for the ratings section
		*
		* @return string
		*/
		function _GetRatingData()
		{
			$output = '';

			$query = 'SELECT posvotes, negvotes
			FROM '.$GLOBALS['tablePrefix']."questions
			WHERE questionid='".$this->_GetId()."'";

			$result = $GLOBALS['AKB_DB']->Query($query);

			if ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$posVotes = $row['posvotes'];
				$negVotes = $row['negvotes'];

				$GLOBALS['TotalVotes'] = $posVotes + $negVotes;

				if ($GLOBALS['TotalVotes'] == 1) {
					$GLOBALS['VotesString'] = GetLang('questVote');
				} else {
					$GLOBALS['VotesString'] = GetLang('questVotes');
				}

				if ($GLOBALS['TotalVotes'] > 0) {
					if ($posVotes > $negVotes) {
						$GLOBALS['PosClass'] = 'highrate';
						$GLOBALS['NegClass'] = 'lowrate';
					} else if ($negVotes > $posVotes) {
						$GLOBALS['PosClass'] = 'lowrate';
						$GLOBALS['NegClass'] = 'highrate';
					} else {
						$GLOBALS['PosClass'] = 'lowrate';
						$GLOBALS['NegClass'] = 'lowrate';
					}

					$GLOBALS['PosVotesPercent'] = floor(($posVotes / $GLOBALS['TotalVotes']) * 100);
					$GLOBALS['NegVotesPercent'] = floor(($negVotes / $GLOBALS['TotalVotes']) * 100);

					$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('QuestionRating');
				} else {
					$output = GetLang('questNoVotes');
				}
			} else {
				$output = GetLang('questNoVotes');
			}

			return $output;
		}

		/**
		* _GetAttachments
		* Get the html for the attachments section of the question page
		*
		* @return string
		*/
		function _GetAttachments()
		{
			$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AttachmentListHeader');
			$attached = false;

			$attach_dir = 'attachments/'.((int) $this->_GetId());

			// If the attachment directory doesn't exist for this question
			// then no questions have ever been uploaded
			if (!is_dir($attach_dir)) {
				return GetLang('questNoAttachments');
			}
			
			if ($dh = opendir($attach_dir)) {
				while (false !== ($file = readdir($dh))) {
					if ($file != '.' && $file != '..' && substr($file, 0, 5) != '_vti_') {
						$data = base64_encode(sprintf('%s|%s', $this->_GetId(), $file));
						$size = filesize($attach_dir.DIRECTORY_SEPARATOR.$file);
						$size = number_format($size);
						$attached = true;

						$GLOBALS['Data'] = urlencode($data);
						$GLOBALS['Filesize'] = $size;
						$GLOBALS['Filename'] = $file;
						$GLOBALS['Fileunits'] = GetLang('questBytes');

						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AttachmentListRow');
					}
				}

				if ($attached) {
					$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AttachmentListFooter');
				} else {
					$output = GetLang('questNoAttachments');
				}
			} else {
				$output = GetLang('questNoAttachments');
			}

			return $output;
		}

		/**
		* _GetRelatedQuestions
		* Get the html for the related questions section of the page
		*
		* @return string
		*/
		function _GetRelatedQuestions()
		{
			// Construct the full text search part of the query
			$fullTextFields = array ('title', 'answer', 'metakeywords');
			
			$output = '';
			if (empty($this->_data)) {
				$this->_SetData();
			}

			$catPasses = array(
				"c.pass = '' OR c.pass is null"
			);
			foreach ($_COOKIE as $k => $v) {
				if (substr($k, 0, 13) == 'akb_cat_pass_') {
					$catid = (int) substr($k, 13);
					$catPasses[] = '(a.categoryid='.$catid." AND c.pass='".$GLOBALS['AKB_DB']->Quote($v)."')";
				}
			}
			
			$workflowQry = "";
			if (validUrl()) {
				$workflowQry = 'AND (q.workflowstatus = \''.WF_STATUS_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_AUTO_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_REPENDING.'\' '.getShowDisapprovedArticleString('OR', 'q.').') ';
			}
			
			if ($this->_data['related'] != '' && $this->_data['related'] != 0) {
				$query = 'SELECT DISTINCT q.questionid, title, workflowstatus
				FROM '.$GLOBALS['tablePrefix'].'questions q, '.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix'].'categories c
				WHERE q.questionid = a.questionid
				AND a.categoryid = c.categoryid
				AND q.questionid IN (\''.str_replace(',', "','", $GLOBALS['AKB_DB']->Quote($this->_data['related'])).'\')
				'.$workflowQry.'
				AND visible=1
				AND (
					'.implode(' OR ', $catPasses).'
				)';
			} else if ($this->_data['detectrelated'] == 1) {
				$query = 'SELECT DISTINCT q.questionid, title, workflowstatus
				FROM '.$GLOBALS['tablePrefix'].'questions q, '.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix']."categories c
				WHERE q.questionid = a.questionid
				AND a.categoryid = c.categoryid
				AND ( ".$GLOBALS['AKB_DB']->FullText($fullTextFields, $this->_data['title'], false)." ) 
				AND q.questionid != ".$this->_data['questionid']."
				AND visible=1
				'.$workflowQry.'
				AND (
					".implode(' OR ', $catPasses).'
				)
				'.$GLOBALS['AKB_DB']->AddLimit(0, 5);
			} else {
				return GetLang('questNoRelatedQuestions');
			}

			$result = $GLOBALS['AKB_DB']->Query($query);

			if ($GLOBALS['AKB_DB']->CountResult($query) == 0) {
				return GetLang('questNoRelatedQuestions');
			} else {
				
				$tmpRow = array();
				$historyQuestionIds = array();
				$validStatus = getShowDisapprovedArticleArray();
				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					if (validUrl()) {
						if (!in_array($row['workflowstatus'], $validStatus)) {
							$tmpRow[] = $row;
						} else {
							$row['title'] = '';
							$tmpRow[] = $row;
							$historyQuestionIds[] = trim($row['questionid']);
						}
					} else {
						$tmpRow[] = $row;
					}
				}
				
				if (sizeof($historyQuestionIds)) {
					$historyQuestionIdsStr = "'" . implode("','", $historyQuestionIds) . "'";
					$historyQuestionIdsQry = "SELECT  DISTINCT questionid, title, lastupdated, workflowstatus 
					FROM {$GLOBALS['tablePrefix']}questions_history
					WHERE (workflowstatus = '".WF_STATUS_AUTO_APPROVED."' OR workflowstatus = '".WF_STATUS_APPROVED."')
					AND questionid IN ($historyQuestionIdsStr)
					ORDER BY lastupdated ASC
					";
					$historyQuestionIdsQryRes = $GLOBALS['AKB_DB']->Query($historyQuestionIdsQry);
					$historyQuestion = array();
					if ($GLOBALS['AKB_DB']->CountResult($historyQuestionIdsQry) > 0) {
						while ($row = $GLOBALS['AKB_DB']->Fetch($historyQuestionIdsQryRes)) {
							$historyQuestion[$row['questionid']] = $row;
						}
					}
				}
				
				$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RelatedListHeader');

				foreach ($tmpRow as $row) {
					if (isset($historyQuestion[$row['questionid']])) {
						$row['title'] = $historyQuestion[$row['questionid']]['title'];
						$row['lastupdated'] = $historyQuestion[$row['questionid']]['lastupdated'];
						$row['workflowstatus'] = $historyQuestion[$row['questionid']]['workflowstatus'];
					}
					if ($row['title'] != '') {
						$GLOBALS['Link'] = GetUrl('question', $row['questionid']);
						if ($GLOBALS['cleanUrls']) {
							$GLOBALS['Link'] .= $GLOBALS['AKB_CLASS_HELPER']->_MakeURLSafe($row['title']);
						}
						$GLOBALS['Text'] = htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RelatedListRow');
					}
				}

				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RelatedListFooter');
			}

			return $output;
		}

		/**
		* _GetComments
		* Get the html for the comments section of the question page
		*
		* @return string
		*/
		function _GetComments()
		{
			if (!$GLOBALS['allowVisitorComments']) {
				return '';
			}

			$count = 0;
			$query = 'SELECT content, name, email
			FROM '.$GLOBALS['tablePrefix'].'comments
			WHERE questionid='.$this->_GetId()."
			AND status='approved'
			ORDER BY commentid ASC";
			
			$result = $GLOBALS['AKB_DB']->Query($query);

			if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
				$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CommentListHeader');

				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					$count++;
					$author = $GLOBALS['AKB_CLASS_HELPER']->PrepareCommentAuthor(htmlspecialchars($row['name'], ENT_QUOTES, $GLOBALS['charset']), $row['email']);

					$GLOBALS['CommentNum'] = $count;
					$GLOBALS['Author'] = $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders($author);
					$GLOBALS['Comment'] = $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders(htmlspecialchars($row['content'], ENT_QUOTES, $GLOBALS['charset']));
					$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CommentListRow');
				}
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CommentListFooter');
			} else {
				$GLOBALS['Link'] = "#content";
				$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('QuestionNoComments');
			}

			return $output;
		}

		/**
		* _GetCategories
		* Get the list of categories which this question is in
		*
		* @return array The ids of the categories that the question is in
		*/
		function _GetCategories()
		{
			$cats = array();
			$query = "SELECT DISTINCT ch.categoryid ";
			$query .= "FROM %scatassoc_history ch, %scategoryassociations ca  ";
			$query .= "WHERE ch.questionid = (%s) ";
			$query .= "AND ch.questionid = ca.questionid ";
			$query .= "AND ch.categoryid = ca.categoryid ";
			$query = sprintf($query, $GLOBALS['tablePrefix'], $GLOBALS['tablePrefix'], $this->_GetId());
			$result = $GLOBALS['AKB_DB']->Query($query);
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$cats[] = $row['categoryid'];
			}
			return $cats;
		}

		/**
		* _GetAnswer
		* Get the html for the question's answer to be displayed
		*
		* @return string
		*/
		function _GetAnswer()
		{
			if (empty($this->_data)) {
				$this->_SetData();
			}

			$output = $this->_data['answer'];
			$arrWords = $GLOBALS['AKB_CLASS_HELPER']->GetGlossaryTerms();
			
			$glossaryTermsSimple = array();
			foreach ($arrWords as $val) {
				$glossaryTermsSimple[] = $val['word'];
			}
			
			// Stop globals and panels being taken literally in question content
			$output = ReplaceString($output, $arrWords, 'GlossaryPopupCallback');

			if (isset($_SESSION['SearchWords'])) {
				$arr = Array();
				foreach ($_SESSION['SearchWords'] as $word) {
					//If this search term has already been highlighted in the glossary, don't do it.
					if (!$this->inGlossary($glossaryTermsSimple,$word)) {
						$arr[] = Array(
							'word' => $word,
							'token' => uniqid('')
						);
					}
				}
				
				$output = ReplaceString($output, $arr, 'SearchTermCallback');
			}

			return $GLOBALS['AKB_CLASS_TEMPLATE']->DisablePlaceholders($output);
		}
		
		/**
		* inGlossary
		* Is the word in a glossary item in any way shape or form?
		*
		* @return string
		*/		
		function inGlossary(&$glossaryArray,$word) {
			foreach ($glossaryArray as $gword) {
				if (strpos($gword,$word) !== false) {
					return true;
				}
			}
			
			return false;
		}

		/**
		* EmailQuestionPage
		* Display the popup to email the question page to someone
		*
		* @return void
		*/
		function EmailQuestionPage()
		{
			if (empty($this->_data)) {
				$this->_SetData();
			}

			$GLOBALS['Title'] = $this->_data['title'];
			$GLOBALS['SafeTitle'] = $GLOBALS['AKB_CLASS_HELPER']->_MakeURLSafe($this->_data['title']);
			$GLOBALS['QuestionId'] = $this->_data['questionid'];
			$GLOBALS['Answer'] = $this->_data['answer'];
			$GLOBALS['Message'] = sprintf(GetLang('questMessage'), $GLOBALS['knowledgebaseName'], GetUrl('question', $this->_GetId()));
			$GLOBALS['Message'] = str_replace('{NL}', "\r\n", $GLOBALS['Message']);
			$GLOBALS['HideMessage'] = 'none';

			$GLOBALS['FormAction'] = GetUrl('question', $this->_GetId(), 'todo=__sendemail');

			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';

			$GLOBALS['AKB_CLASS_TEMPLATE']->disabledEmbeddedTemplateOverride = true;

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('EmailQuestion');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* UpdateEmailCount
		* Increment the counter of how many times this question has been emailed
		*
		* @return void
		*/
		function UpdateEmailCount($QuestionId)
		{
			// Update the field that stores how many times a question has been emailed
			$query = sprintf("update %squestions set emailed=emailed+1 where questionid='%d'", $GLOBALS['tablePrefix'], $QuestionId);
			$GLOBALS['AKB_DB']->Query($query);
		}

		/**
		* SendQuestionEmail
		* Send the actual email for the send to a friend email
		*
		* @return void
		*/
		function SendQuestionEmail()
		{
			$fromName = $_POST['FromName'];
			$fromEmail = $_POST['FromEmail'];
			$toName = $_POST['ToName'];
			$toEmail = $_POST['ToEmail'];
			$message = sprintf(GetLang('questMessage'), $GLOBALS['knowledgebaseName'], GetUrl('question', $this->_GetId()));
			$message = str_replace('{NL}', "\r\n", $message);

			$GLOBALS['ImagePath'] = $GLOBALS['pathToKB'].'/templates/'.$GLOBALS['template'].'/Images';

			$title = sprintf('%s %s', $fromName, GetLang('questHasRequested'));
			$message = str_replace('{{ToName}}', $toName, $message);

			$sendTo = (!empty($toName)) ? "$toName <$toEmail>" : $toEmail;

			$email = new Email_API();
			setEmailVars($email);
			
			$email->Set('CharSet', $GLOBALS['charset']);
			$email->From($fromEmail, $fromName);
			$email->Set('Subject', $title);
			$email->AddBody('text', $message);
			$email->AddRecipient($toEmail, $toName, 't');
			$email_result = $email->Send();

			// If the email was sent ok, update the number of emails sent
			if ($email_result['success']) {
				$this->UpdateEmailCount($this->_GetId());
			}

			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';

			$GLOBALS['HideForm'] = 'none';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('EmailQuestion');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SendSubscriberEmails
		*
		* Sends emails to subscribers when a question is updated
		*
		* @return void
		* @param questionid integer
		*/
		function SendSubscriberEmails($questionid=0)
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('question', 'edit')) {
				$this->NoPermission();
				return;
			}

			if ($questionid <= 0) {
				return false;
			}

			if (!is_numeric($questionid)) {
				return false;
			}

			$query = "SELECT subscriberid, email, confirmcode, subscribedate, questionid
			FROM ".$GLOBALS['tablePrefix']."subscribers
			WHERE confirmed=1
			AND questionid=".$questionid;

			// If we have a low number of emails, just send them straight out
			$result = $GLOBALS['AKB_DB']->Query($query);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Email.Subscribe');
			if ($GLOBALS['AKB_DB']->CountResult($query) <= SUBSCRIBER_EMAIL_THRESHOLD) {
				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					$GLOBALS['QuestionLink'] = GetUrl('question', $row['questionid'], '', false);
					$get = 'todo=__unsubscribe&id='.$row['subscriberid'].'&confirmcode='.$row['confirmcode'];
					$GLOBALS['UnsubscribeLink'] = GetUrl('question', $row['questionid'], $get, false);
					$GLOBALS['SubscribeDate'] = date('d-m-Y', strtotime($row['subscribedate']));
					$GLOBALS['QuestionTitle'] = $_POST['title'];

					$subject = GetLang('SubscribedQuestionUpdated');
					$body = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

					$email = new Email_API();
					setEmailVars($email);

					$email->Set('CharSet', $GLOBALS['charset']);
					$email->From($GLOBALS['contactEmail']);
					$email->Set('Subject', $subject);
					$email->AddBody('text', $body);
					$email->AddRecipient($row['email'], '', 't');
					$email_result = $email->Send();
				}
			}
		}
		
		/**
		* CommentPage
		* Show the page to allow a user to post a comment
		*
		* @return void
		*/
		function CommentPage($load_from_session=false)
		{
			if (empty($this->_data)) {
				$this->_SetData();
			}

			if ($load_from_session) {
				$GLOBALS['CommentName'] = $_SESSION['comment']['name'];
				$GLOBALS['CommentEmail'] = $_SESSION['comment']['email'];
				$GLOBALS['CommentContent'] = $_SESSION['comment']['comment'];
			} else {
				$GLOBALS['CommentName'] = '';
				$GLOBALS['CommentEmail'] = '';
				$GLOBALS['CommentContent'] = '';
			}

			$GLOBALS['PageTitle'] = sprintf(GetLang('questPostCommentForQuestion'), $GLOBALS['Title']);
			$GLOBALS['QuestionId'] = $this->_GetId();
			$GLOBALS['CommentFormAction'] = GetUrl('question', $this->_GetId(), 'todo=__savecomment#content');
			$GLOBALS['ContinueUrl'] = '#';
			$GLOBALS['HideMessage'] = 'none';
			$GLOBALS['HideForm'] = 'block';

			if ($GLOBALS['useCaptchaCheck']) {
				// Generate our captcha (the html)
				$captcha = new AKB_CAPTCHA();
				$captcha->generateSecret(CAPTCHA_LENGTH);
				$captcha->urlPrefix = GetUrl('question', $this->_GetId(), 'todo=__captcha');
				$GLOBALS['AKB_CAPTCHA'] = $captcha->generateHtml();

				$GLOBALS['ShowCaptcha'] = 'table-row';
			} else {
				$GLOBALS['ShowCaptcha'] = 'none';
				$GLOBALS['AKB_CAPTCHA'] = '';
			}
		}

		/**
		* showCaptchaImg
		* Show the CAPTCHA image
		*
		* @return void
		*/
		function showCaptchaImg($offset)
		{
			$col1s = array (
				'#ff0000',
				'#00ff00',
				'#0000ff',
			);

			$captcha = new AKB_CAPTCHA();
			$captcha->loadSecret();
			$captcha->imgDir = dirname(__FILE__).'/../../templates/'.$GLOBALS['template'].'/Images/captcha';
			$captcha->fontFile = $captcha->PickRandomFile(dirname(__FILE__).'/../../lib/fonts', 'ttf');
			$captcha->RandFillType();

			$captcha->bgCol1		= $col1s[array_rand($col1s)];
			$captcha->bgCol2		= '#bcbcbc';

			ob_start();
			// send several headers to make sure the image is not cached
			// Date in the past
			header('Expires: Mon, 23 Jul 1993 05:00:00 GMT');

			// always modified
			header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');

			// HTTP/1.1
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);

			header('Content-type: image/png');

			$captcha->showImg($offset);
			$captcha_img = ob_get_contents();
			ob_end_clean();

			echo $captcha_img;
		}

		/**
		* SaveComment
		* Add a comment to the database and display a confirmation
		*
		* @return void
		*/
		function SaveComment()
		{
			// Save the comment
			$id = $this->_GetId();
			$_POST['status'] = 'pending';
			if (empty($this->_data)) {
				$this->_SetData();
			}
			
			// Check to see if there is anything in the comment
			if (isset($_POST['content']) && !empty($_POST['content'])) {
				// Check to make sure that if we are using the captcha checks
				// that the captcha check actually passes
				if ($GLOBALS['useCaptchaCheck'] == false || ( isset($_POST['captcha']) && isset($_SESSION['captchaSecret']) && $_POST['captcha'] == $_SESSION['captchaSecret']) ) {
					$GLOBALS['commentPageTitle'] = GetLang('questCommentPosted');
					if ($GLOBALS['autoApproveComments'] == true) {
						$_POST['status'] = 'approved';
						$GLOBALS['commentMessage'] = GetLang('questCommentPosted2');
					} else {
						$GLOBALS['commentMessage'] = GetLang('questCommentPosted1');
					}
					
					$comment = new API_COMMENT();
					$newId = $comment->create();
					// If the admin has switched on sending an email on a comment then send an email
					if (isset($GLOBALS['sendCommentEmail']) && $GLOBALS['sendCommentEmail']) {
						$this->SendComment($newId);
					}
				} else {
					$GLOBALS['commentPageTitle'] = GetLang('questCommentRejected');
					$GLOBALS['commentMessage'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['commentMessage'] .= GetLang('questCommentRejectedCaptcha');
				}
			} else {
				$GLOBALS['commentPageTitle'] = GetLang('questCommentRejected');
				$GLOBALS['commentMessage'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['commentMessage'] .= GetLang('questCommentRejectedEmpty');
			}
			
			$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';
			$GLOBALS['HidePanels'][] = 'QuestionAuthPanel';
			
			$GLOBALS['CatCrumbs'] = "none";

			$GLOBALS['HideMessage'] = 'block';
			$GLOBALS['HideForm'] = 'block';
			$GLOBALS['QuestionId'] = $id;
			$GLOBALS['ContinueUrl'] = GetUrl('question', $id);
			$GLOBALS['SafeTitle'] = $GLOBALS['AKB_CLASS_HELPER']->_MakeURLSafe($this->_data['title']);

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SendComment
		* Email a comment to the site admin or the users in the selected
		* contact group
		*
		* @return void
		*/
		function SendComment($commentId = 0)
		{
			if (!isset($_POST['questionid'])) {
				return false;
			}
			$question_id = (int) $_POST['questionid'];

			// Get some more information to make the email a little more informative
			$query = 'SELECT name, title
			FROM '.$GLOBALS['tablePrefix'].'categories c, '.$GLOBALS['tablePrefix'].'questions q, '.$GLOBALS['tablePrefix'].'categoryassociations a
			WHERE c.categoryid = a.categoryid
			AND q.questionid = a.questionid
			AND q.questionid = '.$question_id;

			$result = $GLOBALS['AKB_DB']->Query($query);
			$row = $GLOBALS['AKB_DB']->Fetch($result);

			// Setup our variables for
			$QuestionURL = GetUrl('question', $question_id);
			if ($commentId <= 0) {
				$commentId = $question_id;
			}
			$EditURL = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=editComment&commentId='.$commentId;
			$Comment = htmlspecialchars(ellipsize($_POST['content'], 65), ENT_QUOTES, $GLOBALS['charset']);

			// Build the email
			$msg = '';
			$msg .= GetLang('questCommentEmail');
			$msg .= $GLOBALS['knowledgebaseName'].' - '.$GLOBALS['pathToKB']."\n\n";
			$msg .= str_repeat('-', 70)."\n";
			$msg .= GetLang('commentQuestionDetails')."\n";
			$msg .= str_repeat('-', strlen(GetLang('commentQuestionDetails')))."\n";
			$msg .= str_pad(GetLang('category'), 15).': '.$row['name']."\n";
			$msg .= str_pad(GetLang('questUrl'), 15).': '.$QuestionURL."\n\n";
			$msg .= str_repeat('-', 70)."\n";
			$msg .= GetLang('commentCommentDetails')."\n";
			$msg .= str_repeat('-', strlen(GetLang('commentCommentDetails')))."\n";
			$msg .= str_pad(GetLang('questFromName'), 15).': '.$_POST['name']."\n";
			$msg .= str_pad(GetLang('questFromEmail'), 15).': '.$_POST['email']."\n";
			$msg .= str_pad(GetLang('commentEdit'), 15).': '.$EditURL."\n";
			$msg .= str_pad(GetLang('questCommentLabel'), 15).': '.$Comment."\n";

			$email = new Email_API();
			setEmailVars($email);
			
			$email->Set('CharSet', $GLOBALS['charset']);
			$email->From($_POST['email'], $_POST['name']);
			$email->Set('Subject', GetLang('questCommentEmail'));
			$email->AddBody('text', $msg);
			$email->AddRecipient($GLOBALS['contactEmail'], '', 't');
			$email_result = $email->Send();
		}

		/**
		* SendUnhelpfulRatingEmail
		*
		* Sends an email to the site admin when a question is rated as unhelpful
		*
		* @return void
		*/
		function SendUnhelpfulRatingEmail()
		{
			if ($GLOBALS['emailOnUnhelpfulRating']) {
				$to = $GLOBALS['contactEmail'];
				$subject = GetLang('EmailUnhelpfulRating');
				$GLOBALS['QuestionURL'] = GetUrl('question', $this->_GetId());
				$GLOBALS['QuestionAdminURL'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=editQuestion&questionid='.$this->_GetId();
				$GLOBALS['Why'] = $_POST['ratingmessage'];
				$GLOBALS['WhyEmail'] = $_POST['ratingemail'];
				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Email.UnhelpfulRating');
				$body = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

				$email = new Email_API();
				setEmailVars($email);
				
				$email->Set('CharSet', $GLOBALS['charset']);
				$email->From($GLOBALS['contactEmail']);
				$email->Set('Subject', GetLang('EmailUnhelpfulRating'));
				$email->AddBody('text', $body);
				$email->AddRecipient($GLOBALS['contactEmail'], '', 't');
				$email_result = $email->Send();
			}
		}

		/**
		* ShowSubscribePage
		*
		* Display the subscribe to question page
		*
		* @return void
		*/
		function ShowSubscribePage()
		{
			$GLOBALS['FormAction'] = GetUrl('question', $this->_GetId(), 'todo=__savesubscription');

			$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';
			$GLOBALS['HidePanels'][] = 'QuestionAuthPanel';
			$GLOBALS['HidePanels'][] = 'CommentSubmitted';
			
			$GLOBALS['CatCrumbs'] = "none";

			$GLOBALS['ContinueUrl'] = '#';
			$GLOBALS['HideMessage'] = 'none';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SaveSubscriptionDetails
		*
		* Save the users subscription details and show a page with confirmation
		* Also sends them an email with confiration details in it
		*
		* @return void
		*/
		function SaveSubscriptionDetails()
		{
			$sub = new API_SUBSCRIBER();
			$_POST['questionid'] = $this->_GetId();
			if ($id = @$sub->create()) {
				$sub->load($id);
				if ($this->SendConfirmSubscriptionEmail($sub)) {
					$GLOBALS['SubMessage'] = GetLang('questSubscribeOk');
				} else {
					$GLOBALS['SubMessage'] = GetLang('questSubscribeFail');
				}
			} else {
				switch (mysql_errno()) {
					case 1062:
						// Duplicate entry error - i.e. they have already subscribed
						$GLOBALS['SubMessage'] = GetLang('questSubscribeFailAlreadySubscribed');
					break;
					default:
						$GLOBALS['SubMessage'] = GetLang('questSubscribeFail');
				}
			}

			$GLOBALS['ContinueUrl'] = GetUrl('question', $this->_GetId());

			$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'QuestionAuthPanel';
			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';
			$GLOBALS['HidePanels'][] = 'CommentSubmitted';
			
			$GLOBALS['CatCrumbs'] = "none";
			
			$GLOBALS['HideForm'] = 'none';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* ShowSubscriptionConfirm
		*
		* Flag a subscriber as being confirmed and show them confirmation
		*
		* @return void
		*/
		function ShowSubscriptionConfirm()
		{
			$_POST['confirmed'] = 1;

			if (!isset($_GET['confirmcode'])) {
				return;
			}
			if (!isset($_GET['id'])) {
				return;
			}

			$sub = new API_SUBSCRIBER();
			$sub->load((int) $_GET['id']);

			if ($sub->loaded && $_GET['confirmcode'] == $sub->confirmcode ) {
				if ($sub->save()) {
					$GLOBALS['SubMessage'] = GetLang('questSubscribeConfirmed');
				} else {
					$GLOBALS['SubMessage'] = GetLang('questSubscribeConfirmFailed');
				}
			} else {
				$GLOBALS['SubMessage'] = GetLang('questSubscribeConfirmFailed');
			}

			$GLOBALS['ContinueUrl'] = GetUrl('question', $this->_GetId());

			$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'QuestionUnsubscribePanel';
			$GLOBALS['HidePanels'][] = 'CommentSubmitted';
			$GLOBALS['HidePanels'][] = 'QuestionAuthPanel';
			
			$GLOBALS['CatCrumbs'] = "none";			

			$GLOBALS['HideForm'] = 'none';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SendConfirmSubscriptionEmail
		*
		* Send the email for the subscriber to confirm their email address
		*
		* @return boolean
		* @param sub object
		*/
		function SendConfirmSubscriptionEmail($sub)
		{
			// If we havn't been passed the right type of object, stop
			if (strtolower(get_class($sub)) != 'api_subscriber') {
				return false;
			}

			// If the subscriber hasn't been loaded from the database, stop
			if (!$sub->loaded) {
				return false;
			}

			// Confirm link
			$get = 'todo=__confirm&id='.$sub->subscriberid.'&confirmcode='.$sub->confirmcode;
			$GLOBALS['ConfirmLink'] = GetUrl('question', $sub->questionid, $get, false);

			// Link to the question
			$GLOBALS['QuestionLink'] = GetUrl('question', $sub->questionid);

			// Body of the email
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Email.ConfirmSubscription');
			$body = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);

			$email = new Email_API();
			setEmailVars($email);
			
			$email->Set('CharSet', $GLOBALS['charset']);
			$email->From($GLOBALS['contactEmail']);
			$email->Set('Subject', GetLang('EmailConfirmSubscribeSubject'));
			$email->AddBody('text', $body);
			$email->AddRecipient($sub->email, '', 't');
			$email_result = $email->Send();

			// Send the email
			if ($email_result['success'] == 1) {
				return true;
			} else {
				return false;
			}
		}

		/**
		* ShowUnsubscribePage
		*
		* Displays a page allowing a user to unsubscribe from either the current
		* question, or all questions they are subscribed to
		*
		* @return void
		*/
		function ShowUnsubscribePage()
		{
			$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';

			$GLOBALS['HideForm'] = 'block';
			$GLOBALS['HideMessage'] = 'none';

			$GLOBALS['PageTitle'] = GetLang('questUnsubscribe');

			$get = 'todo=__unsubscribeconfirm';
			$GLOBALS['FormAction'] = GetUrl('question', $this->_GetId(), $get);

			$GLOBALS['ConfirmCode'] = htmlspecialchars($_GET['confirmcode'], ENT_QUOTES, $GLOBALS['charset']);
			$GLOBALS['SubscriberId'] = htmlspecialchars($_GET['id'], ENT_QUOTES, $GLOBALS['charset']);

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SaveUnsubscribe
		*
		* Save the unsubscription of the user and display a notification
		*
		* @return void
		*/
		function SaveUnsubscribe()
		{
			$GLOBALS['HidePanels'][] = 'ViewQuestionPanel';
			$GLOBALS['HidePanels'][] = 'SearchResultsPanel';
			$GLOBALS['HidePanels'][] = 'SubmitCommentPanel';
			$GLOBALS['HidePanels'][] = 'QuestionSubscribePanel';

			$GLOBALS['PageTitle'] = GetLang('questUnsubscribe');

			$GLOBALS['HideForm'] = 'none';
			$GLOBALS['HideMessage'] = 'block';
			$GLOBALS['Message'] = '';
			$GLOBALS['ContinueUrl'] = GetUrl('question', $this->_GetId());

			switch ($_POST['type']) {
				case 'all':
					// Since the API doesn't have a delete ability on anything
					// other than the primary key, we have to use sql here
					// specifically to delete based on the email of the user
					$sub = new API_SUBSCRIBER();
					$sub->load((int) $_POST['subscriberid']);
					if ($sub->loaded) {
						$query = 'DELETE FROM '.$GLOBALS['tablePrefix']."subscribers
						WHERE email='".$GLOBALS['AKB_DB']->Quote($sub->email)."'";
						if ($sub->confirmcode == $_POST['confirmcode']
							&& $GLOBALS['AKB_DB']->Query($query)) {
							$GLOBALS['Message'] = GetLang('questUnsubscribeSuccessAll');
						} else {
							$GLOBALS['Message'] = GetLang('questUnsubscribeFailed');
						}
					} else {
						$GLOBALS['Message'] = GetLang('questNotSubscribed');
					}
				break;
				case 'single':
					$sub = new API_SUBSCRIBER();
					$sub->load((int) $_POST['subscriberid']);
					if ($sub->loaded) {
						if ($sub->confirmcode == $_POST['confirmcode']
							&& $sub->delete((int) $_POST['subscriberid'])) {
							$GLOBALS['Message'] = GetLang('questUnsubscribeSuccessSingle');
						} else {
							$GLOBALS['Message'] = GetLang('questUnsubscribeFailed');
						}
					} else {
						$GLOBALS['Message'] = GetLang('questNotSubscribed');
					}
				break;
			}

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetPageTitle($GLOBALS['knowledgebaseName']);
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('Questions');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* GetBreadCrumbs
		* Get the html for all the possible paths to this question
		*
		* @return string
		*/
		function GetBreadCrumbs()
		{
			$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('QuestionBreadCrumbHeader');
			$cats = $this->_GetCategories();
			$GLOBALS['Link'] = $GLOBALS['pathToKB'].'/';
			$GLOBALS['Text'] = GetLang('hpHome');
			$GLOBALS['Target'] = '_top';
			$home = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkWithTarget');

			foreach ($cats as $catid) {
				$text = $GLOBALS['AKB_CLASS_HELPER']->GetCategoryTrail($catid, true);
				if (!$text) {
					continue;
				} 

				$GLOBALS['Text'] = $home.$text;
				$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('QuestionBreadCrumbRow');
			}

			$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('QuestionBreadCrumbFooter');
			return $output;
		}

		/**
		* CheckCommentForm
		*
		* Check that the comment form has been filled out correctly
		*
		* @return bool Has the form been filled out correctly
		*/
		function CheckCommentForm()
		{
			// Verify the CAPTCHA is correct
			if ($GLOBALS['useCaptchaCheck'] == true) {
				
				if (!isset($_POST['captcha'])) {
					$GLOBALS['commentMessage'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['commentMessage'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}

				$captcha = new AKB_CAPTCHA();
				$captcha->loadSecret();

				if (!isset($captcha->secret) || empty($captcha->secret)) {
					$GLOBALS['commentMessage'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['commentMessage'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}

				if ($_POST['captcha'] != $captcha->secret) {
					$GLOBALS['commentMessage'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['commentMessage'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}
				
				if ($_SESSION['captchaLoads'] > $captcha->maxLoads) {
					$GLOBALS['commentMessage'] = GetLang('questCommentRejected').'. ';
					$GLOBALS['commentMessage'] .= GetLang('questCommentRejectedCaptcha');
					return false;
				}
			}

			// Check the form fields
			if (!empty($_POST['email']) && !is_email_address($_POST['email'])) {
				$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['Message'] .= GetLang('conInvalidEmail');
				return false;
			}

			if (empty($_POST['content'])) {
				$GLOBALS['Message'] = GetLang('questCommentRejected').'. ';
				$GLOBALS['Message'] .= GetLang('conQuestionRequired');
				return false;
			}
			
			return true;
		}

		/**
		* EditEntry
		*
		* Redirects to the admin area to edits the question entry
		*
		* @return void
		*/
		function EditEntry()
		{
			$link = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=editQuestion&questionid='.$this->_GetId();
			header("Location: $link");
		}
		
		/**
		* QuestionHasAuthCat
		*
		* Checks to see whether the question id and all of its categories have access by the logged in user.
		*
		* @return boolean
		*/		
		function QuestionHasAuthCat() {
			
			//Get the categories this user can access.
			$GLOBALS['AKB_CLASS_HELPER']->categoryRestrictOverride = true;
			$GLOBALS['AKB_CLASS_HELPER']->catsCached = false;
			$permittedCats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
			
			//Get the categories associated with this question
			$questionCats = $GLOBALS['AKB_CLASS_CATEGORIES']->GetCategoriesForQuestion($this->_GetId());
			
			return (bool)array_intersect($questionCats,$permittedCats);
		}
		
		/**
		* QuestionHasAuthArticle
		*
		* Checks to see whether any of the groups that the current user is logged in has acces to this question
		*
		* @return boolean
		*/		
		function QuestionHasAuthArticle() {
			return true;			
		}		
	}

?>
